﻿using Amiable.Core.BotEvents.Models;
using Amiable.SDK.Enum;
using Amiable.SDK.EventArgs;
using Amiable.SDK.Interface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace Amiable.Core.BotEvents
{
    public class EnableEvent : IPluginEvent
    {
        public AmiableEventType EventType => AmiableEventType.PluginEnable;

        public void Process(AmiableEventArgs e)
        {
            ConsoleManager.Show();
            Console.Title = "Ami·XdXdBot";
            Console.WriteLine($"配置文件位置:{@"Ami\XdXdBot\appsettings.json"}");
            Console.WriteLine($"首次使用请修改Port(端口默认为11451)");
            Console.WriteLine($"修改发送群(EnableGroups)以及相应仓库(EnableRepos)");
            Console.WriteLine($"以及Robot QQ号(部分单Q框架可以不用填写)");
            Console.WriteLine($"服务器需要开启安全组，且Git需要配置好Webhooks");
            Console.WriteLine($"重启或私聊发送 XdXdBotReload 既可重新加载非HTTP监听类配置。");
            Console.WriteLine($"感谢使用!Ami XdXdBot < 实在不知道怎么取名字");
            Console.WriteLine($"有什么需要可以联系赫尔1767407822");
            Console.WriteLine($"本项目地址https://gitee.com/heerkaisair/xd-xd-bot");
            XdXd.LoadConfig();

            XdXd.Api = e.ApiWrapper;


            if (XdXd.Listener == null)
            {
                XdXd.Listener = new HttpListener();

                if (!HttpListener.IsSupported)
                {
                    e.ApiWrapper.OutPutLog("当前系统不支持!");
                    return;
                }

                HttpListener listener = new HttpListener();
                var port = XdXd.Configuration.Port;

                listener.Prefixes.Add($"http://+:{port}/");
                listener.Start();

                Console.WriteLine($"{port}端口已启动HTTP服务!");
                Console.WriteLine($"开始监听HTTP");
                listener.BeginGetContext(Handle, listener);
            }
        }

        /// <summary>
        /// 处理程序
        /// </summary>
        /// <param name="ar"></param>
        private static void Handle(IAsyncResult ar)
        {
            var listener = ar.AsyncState as HttpListener;
            if (listener.IsListening is false)
                return;

            Console.WriteLine("收到了一条推送");
            DateTime datetime = DateTime.Now;
            HttpListenerContext context = listener.EndGetContext(ar);

            Console.WriteLine($"来自:{context.Request.RemoteEndPoint}");
            using (var json = new StreamReader(context.Request.InputStream))
            {
                var text = json.ReadToEnd();

                Root giteepush = JsonSerializer.Deserialize<Root>
                (text, new JsonSerializerOptions()
                {
                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

                Console.WriteLine($"仓库消息:{giteepush.repository.full_name}");

                if (XdXd.Configuration.EnableRepos.Contains(giteepush.repository.full_name) is false)
                {
                    listener.BeginGetContext(Handle, listener);
                    return;
                }

                giteepush.commits.ForEach(x =>
                {
                    Console.WriteLine($"Commit:{x.message}");
                    Console.WriteLine(x.author.name);
                });

                var sb = new StringBuilder();
                sb.AppendLine($"> XdXdBot!!");
                sb.AppendLine($"> 发现了一个Push!!!");
                sb.AppendLine($"> {datetime.ToShortTimeString()}");
                sb.AppendLine($"> 仓库:{giteepush.repository.full_name}");
                sb.AppendLine($"> 仓库描述:{giteepush.repository.description}");
                sb.AppendLine($"> Commits提交信息:");
                giteepush.commits.ForEach(x => { sb.AppendLine($"> {x.message}"); });

                Console.WriteLine(sb.ToString());

                Task.Factory.StartNew(() =>
                {
                    Console.WriteLine("创建发送队列...");
                    foreach (var group in XdXd.Configuration.EnableGroups)
                    {
                        Console.WriteLine($"正在向群{group}推送消息");

                        XdXd.Api.SetData(new() { Robot = XdXd.Configuration.Robot });
                        XdXd.Api.SendGroupMessage(group.ToString(), sb.ToString());
                        Console.WriteLine($"群{group}推送完成");

                        Thread.Sleep(4000);
                    }
                });
            }

            context.Response.StatusCode = 200;
            var returnByteArr = Encoding.UTF8.GetBytes("OK");
            using (var stream = context.Response.OutputStream)
            {
                stream.Write(returnByteArr, 0, returnByteArr.Length);
            }

            context.Response.Close();
            Console.WriteLine($"开启下一次监听...");
            listener.BeginGetContext(Handle, listener);
        }
    }
}